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