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