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