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