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