Merge the t-gnus-6_17-quimby branch.
[elisp/gnus.git-] / lisp / mm-url.el
1 ;;; mm-url.el --- a wrapper of url functions/commands for Gnus
2
3 ;; Copyright (C) 2001, 2002, 2003, 2004, 2005,
4 ;;   2006 Free Software Foundation, Inc.
5
6 ;; Author: Shenghuo Zhu <zsh@cs.rochester.edu>
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
12 ;; by the Free Software Foundation; either version 2, or (at your
13 ;; option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; 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., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
24
25 ;;; Commentary:
26
27 ;; Some codes are stolen from w3 and url packages. Some are moved from
28 ;; nnweb.
29
30 ;; TODO: Support POST, cookie.
31
32 ;;; Code:
33
34 (eval-when-compile (require 'cl))
35
36 (require 'nnheader) ;; for `mm-char-or-char-int-p'.
37 (require 'gnus)
38
39 (eval-and-compile
40   (autoload 'exec-installed-p "path-util"))
41
42 (eval-when-compile
43   (if (featurep 'xemacs)
44       (require 'timer-funcs)
45     (require 'timer)))
46
47 (defvar url-current-object)
48 (defvar url-package-name)
49 (defvar url-package-version)
50
51 (defgroup mm-url nil
52   "A wrapper of url package and external url command for Gnus."
53   :group 'gnus)
54
55 (defcustom mm-url-use-external (not
56                                 (condition-case nil
57                                     (require 'url)
58                                   (error nil)))
59   "*If non-nil, use external grab program `mm-url-program'."
60   :version "22.1"
61   :type 'boolean
62   :group 'mm-url)
63
64 (defvar mm-url-predefined-programs
65   '((wget "wget" "--user-agent=mm-url" "-q" "-O" "-")
66     (w3m  "w3m" "-dump_source")
67     (lynx "lynx" "-source")
68     (curl "curl" "--silent" "--user-agent mm-url" "--location")))
69
70 (defcustom mm-url-program
71   (cond
72    ((exec-installed-p "wget") 'wget)
73    ((exec-installed-p "w3m") 'w3m)
74    ((exec-installed-p "lynx") 'lynx)
75    ((exec-installed-p "curl") 'curl)
76    (t "GET"))
77   "The url grab program.
78 Likely values are `wget', `w3m', `lynx' and `curl'."
79   :version "22.1"
80   :type '(choice
81           (symbol :tag "wget" wget)
82           (symbol :tag "w3m" w3m)
83           (symbol :tag "lynx" lynx)
84           (symbol :tag "curl" curl)
85           (string :tag "other"))
86   :group 'mm-url)
87
88 (defcustom mm-url-arguments nil
89   "The arguments for `mm-url-program'."
90   :version "22.1"
91   :type '(repeat string)
92   :group 'mm-url)
93
94 \f
95 ;;; Internal variables
96
97 (defvar mm-url-package-name
98   (gnus-replace-in-string
99    (gnus-replace-in-string gnus-version " v.*$" "")
100    " " "-"))
101
102 (defvar mm-url-package-version gnus-version-number)
103
104 ;; Stolen from w3.
105 (defvar mm-url-html-entities
106   '(
107     ;;(excl        .  33)
108     (quot        .  34)
109     ;;(num         .  35)
110     ;;(dollar      .  36)
111     ;;(percent     .  37)
112     (amp         .  38)
113     (rsquo       .  39)                 ; should be U+8217
114     ;;(apos        .  39)
115     ;;(lpar        .  40)
116     ;;(rpar        .  41)
117     ;;(ast         .  42)
118     ;;(plus        .  43)
119     ;;(comma       .  44)
120     ;;(period      .  46)
121     ;;(colon       .  58)
122     ;;(semi        .  59)
123     (lt          .  60)
124     ;;(equals      .  61)
125     (gt          .  62)
126     ;;(quest       .  63)
127     ;;(commat      .  64)
128     ;;(lsqb        .  91)
129     ;;(rsqb        .  93)
130     (uarr        .  94)                 ; should be U+8593
131     ;;(lowbar      .  95)
132     (lsquo       .  96)                 ; should be U+8216
133     (lcub        . 123)
134     ;;(verbar      . 124)
135     (rcub        . 125)
136     (tilde       . 126)
137     (nbsp        . 160)
138     (iexcl       . 161)
139     (cent        . 162)
140     (pound       . 163)
141     (curren      . 164)
142     (yen         . 165)
143     (brvbar      . 166)
144     (sect        . 167)
145     (uml         . 168)
146     (copy        . 169)
147     (ordf        . 170)
148     (laquo       . 171)
149     (not         . 172)
150     (shy         . 173)
151     (reg         . 174)
152     (macr        . 175)
153     (deg         . 176)
154     (plusmn      . 177)
155     (sup2        . 178)
156     (sup3        . 179)
157     (acute       . 180)
158     (micro       . 181)
159     (para        . 182)
160     (middot      . 183)
161     (cedil       . 184)
162     (sup1        . 185)
163     (ordm        . 186)
164     (raquo       . 187)
165     (frac14      . 188)
166     (frac12      . 189)
167     (frac34      . 190)
168     (iquest      . 191)
169     (Agrave      . 192)
170     (Aacute      . 193)
171     (Acirc       . 194)
172     (Atilde      . 195)
173     (Auml        . 196)
174     (Aring       . 197)
175     (AElig       . 198)
176     (Ccedil      . 199)
177     (Egrave      . 200)
178     (Eacute      . 201)
179     (Ecirc       . 202)
180     (Euml        . 203)
181     (Igrave      . 204)
182     (Iacute      . 205)
183     (Icirc       . 206)
184     (Iuml        . 207)
185     (ETH         . 208)
186     (Ntilde      . 209)
187     (Ograve      . 210)
188     (Oacute      . 211)
189     (Ocirc       . 212)
190     (Otilde      . 213)
191     (Ouml        . 214)
192     (times       . 215)
193     (Oslash      . 216)
194     (Ugrave      . 217)
195     (Uacute      . 218)
196     (Ucirc       . 219)
197     (Uuml        . 220)
198     (Yacute      . 221)
199     (THORN       . 222)
200     (szlig       . 223)
201     (agrave      . 224)
202     (aacute      . 225)
203     (acirc       . 226)
204     (atilde      . 227)
205     (auml        . 228)
206     (aring       . 229)
207     (aelig       . 230)
208     (ccedil      . 231)
209     (egrave      . 232)
210     (eacute      . 233)
211     (ecirc       . 234)
212     (euml        . 235)
213     (igrave      . 236)
214     (iacute      . 237)
215     (icirc       . 238)
216     (iuml        . 239)
217     (eth         . 240)
218     (ntilde      . 241)
219     (ograve      . 242)
220     (oacute      . 243)
221     (ocirc       . 244)
222     (otilde      . 245)
223     (ouml        . 246)
224     (divide      . 247)
225     (oslash      . 248)
226     (ugrave      . 249)
227     (uacute      . 250)
228     (ucirc       . 251)
229     (uuml        . 252)
230     (yacute      . 253)
231     (thorn       . 254)
232     (yuml        . 255)
233
234     ;; Special handling of these
235     (frac56      . "5/6")
236     (frac16      . "1/6")
237     (frac45      . "4/5")
238     (frac35      . "3/5")
239     (frac25      . "2/5")
240     (frac15      . "1/5")
241     (frac23      . "2/3")
242     (frac13      . "1/3")
243     (frac78      . "7/8")
244     (frac58      . "5/8")
245     (frac38      . "3/8")
246     (frac18      . "1/8")
247
248     ;; The following 5 entities are not mentioned in the HTML 2.0
249     ;; standard, nor in any other HTML proposed standard of which I
250     ;; am aware.  I am not even sure they are ISO entity names.  ***
251     ;; Hence, some arrangement should be made to give a bad HTML
252     ;; message when they are seen.
253     (ndash       .  45)
254     (mdash       .  45)
255     (emsp        .  32)
256     (ensp        .  32)
257     (sim         . 126)
258     (le          . "<=")
259     (agr         . "alpha")
260     (rdquo       . "''")
261     (ldquo       . "``")
262     (trade       . "(TM)")
263     ;; To be done
264     ;; (shy      . ????) ; soft hyphen
265     )
266   "*An assoc list of entity names and how to actually display them.")
267
268 (defconst mm-url-unreserved-chars
269   '(
270     ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z
271     ?A ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z
272     ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
273     ?- ?_ ?. ?! ?~ ?* ?' ?\( ?\))
274   "A list of characters that are _NOT_ reserved in the URL spec.
275 This is taken from RFC 2396.")
276
277 (defun mm-url-load-url ()
278   "Load `url-insert-file-contents'."
279   (unless (condition-case ()
280               (progn
281                 (require 'url-handlers)
282                 (require 'url-parse)
283                 (require 'url-vars))
284             (error nil))
285     ;; w3-4.0pre0.46 or earlier version.
286     (require 'w3-vars)
287     (require 'url)))
288
289 ;;;###autoload
290 (defun mm-url-insert-file-contents (url)
291   "Insert file contents of URL.
292 If `mm-url-use-external' is non-nil, use `mm-url-program'."
293   (if mm-url-use-external
294       (progn
295         (if (string-match "^file:/+" url)
296             (insert-file-contents (substring url (1- (match-end 0))))
297           (mm-url-insert-file-contents-external url))
298         (goto-char (point-min))
299         (if (fboundp 'url-generic-parse-url)
300             (setq url-current-object
301                   (url-generic-parse-url url)))
302         (list url (buffer-size)))
303     (mm-url-load-url)
304     (let ((name buffer-file-name)
305           (url-request-extra-headers (list (cons "Connection" "Close")))
306           (url-package-name (or mm-url-package-name
307                                 url-package-name))
308           (url-package-version (or mm-url-package-version
309                                    url-package-version))
310           result)
311       (setq result (url-insert-file-contents url))
312       (save-excursion
313         (goto-char (point-min))
314         (while (re-search-forward "\r 1000\r ?" nil t)
315           (replace-match "")))
316       (setq buffer-file-name name)
317       (if (and (fboundp 'url-generic-parse-url)
318                (listp result))
319           (setq url-current-object (url-generic-parse-url
320                                     (car result))))
321       result)))
322
323 ;;;###autoload
324 (defun mm-url-insert-file-contents-external (url)
325   "Insert file contents of URL using `mm-url-program'."
326   (let (program args)
327     (if (symbolp mm-url-program)
328         (let ((item (cdr (assq mm-url-program mm-url-predefined-programs))))
329           (setq program (car item)
330                 args (append (cdr item) (list url))))
331       (setq program mm-url-program
332             args (append mm-url-arguments (list url))))
333     (unless (eq 0 (apply 'call-process program nil t nil args))
334       (error "Couldn't fetch %s" url))))
335
336 (defvar mm-url-timeout 30
337   "The number of seconds before timing out an URL fetch.")
338
339 (defvar mm-url-retries 10
340   "The number of retries after timing out when fetching an URL.")
341
342 (defun mm-url-insert (url &optional follow-refresh)
343   "Insert the contents from an URL in the current buffer.
344 If FOLLOW-REFRESH is non-nil, redirect refresh url in META."
345   (let ((times mm-url-retries)
346         (done nil)
347         (first t)
348         result)
349     (while (and (not (zerop (decf times)))
350                 (not done))
351       (with-timeout (mm-url-timeout)
352         (unless first
353           (message "Trying again (%s)..." (- mm-url-retries times)))
354         (setq first nil)
355         (if follow-refresh
356             (save-restriction
357               (narrow-to-region (point) (point))
358               (mm-url-insert-file-contents url)
359               (goto-char (point-min))
360               (when (re-search-forward
361                      "<meta[ \t\r\n]*http-equiv=\"Refresh\"[^>]*URL=\\([^\"]+\\)\"" nil t)
362                 (let ((url (match-string 1)))
363                   (delete-region (point-min) (point-max))
364                   (setq result (mm-url-insert url t)))))
365           (setq result (mm-url-insert-file-contents url)))
366         (setq done t)))
367     result))
368
369 (defun mm-url-decode-entities ()
370   "Decode all HTML entities."
371   (goto-char (point-min))
372   (while (re-search-forward "&\\(#[0-9]+\\|[a-z]+[0-9]*\\);" nil t)
373     (let ((elem (if (eq (aref (match-string 1) 0) ?\#)
374                         (let ((c
375                                (string-to-number (substring
376                                                   (match-string 1) 1))))
377                           (if (mm-char-or-char-int-p c) c 32))
378                       (or (cdr (assq (intern (match-string 1))
379                                      mm-url-html-entities))
380                           ?#))))
381       (unless (stringp elem)
382         (setq elem (char-to-string elem)))
383       (replace-match elem t t))))
384
385 (defun mm-url-decode-entities-nbsp ()
386   "Decode all HTML entities and &nbsp; to a space."
387   (let ((mm-url-html-entities (cons '(nbsp . 32) mm-url-html-entities)))
388     (mm-url-decode-entities)))
389
390 (defun mm-url-decode-entities-string (string)
391   (with-temp-buffer
392     (insert string)
393     (mm-url-decode-entities)
394     (buffer-string)))
395
396 (defun mm-url-form-encode-xwfu (chunk)
397   "Escape characters in a string for application/x-www-form-urlencoded.
398 Blasphemous crap because someone didn't think %20 was good enough for encoding
399 spaces.  Die Die Die."
400   ;; This will get rid of the 'attributes' specified by the file type,
401   ;; which are useless for an application/x-www-form-urlencoded form.
402   (if (consp chunk)
403       (setq chunk (cdr chunk)))
404
405   (mapconcat
406    (lambda (char)
407      (cond
408       ((= char ?  ) "+")
409       ((memq char mm-url-unreserved-chars) (char-to-string char))
410       (t (upcase (format "%%%02x" char)))))
411    ;; Fixme: Should this actually be accepting multibyte?  Is there a
412    ;; better way in XEmacs?
413    (if (featurep 'mule)
414        (encode-coding-string chunk
415                              (if (fboundp 'find-coding-systems-string)
416                                  (car (find-coding-systems-string chunk))
417                                buffer-file-coding-system))
418      chunk)
419    ""))
420
421 (defun mm-url-encode-www-form-urlencoded (pairs)
422   "Return PAIRS encoded for forms."
423   (mapconcat
424    (lambda (data)
425      (concat (mm-url-form-encode-xwfu (car data)) "="
426              (mm-url-form-encode-xwfu (cdr data))))
427    pairs "&"))
428
429 (defun mm-url-fetch-form (url pairs)
430   "Fetch a form from URL with PAIRS as the data using the POST method."
431   (mm-url-load-url)
432   (let ((url-request-data (mm-url-encode-www-form-urlencoded pairs))
433         (url-request-method "POST")
434         (url-request-extra-headers
435          '(("Content-type" . "application/x-www-form-urlencoded"))))
436     (url-insert-file-contents url)
437     (setq buffer-file-name nil))
438   t)
439
440 (defun mm-url-fetch-simple (url content)
441   (mm-url-load-url)
442   (let ((url-request-data content)
443         (url-request-method "POST")
444         (url-request-extra-headers
445          '(("Content-type" . "application/x-www-form-urlencoded"))))
446     (url-insert-file-contents url)
447     (setq buffer-file-name nil))
448   t)
449
450 (defun mm-url-remove-markup ()
451   "Remove all HTML markup, leaving just plain text."
452   (goto-char (point-min))
453   (while (search-forward "<!--" nil t)
454     (delete-region (match-beginning 0)
455                    (or (search-forward "-->" nil t)
456                        (point-max))))
457   (goto-char (point-min))
458   (while (re-search-forward "<[^>]+>" nil t)
459     (replace-match "" t t)))
460
461 (provide 'mm-url)
462
463 ;;; mm-url.el ends here